package com.example.cloudmusic.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.cloudmusic.home.model.*
import com.example.cloudmusic.home.repository.DataSourceType
import com.example.cloudmusic.home.repository.HomeRepository
import com.example.cloudmusic.home.repository.HomeRepositoryProvider
import com.example.cm_base.BaseViewModel
import com.example.cm_player.manager.PlayerManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 首页ViewModel，负责加载和管理首页数据
 */
class HomeViewModel : BaseViewModel() {
    private val _sections = MutableLiveData<List<HomeItem>>()
    val sections: LiveData<List<HomeItem>> = _sections

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading


    private val _errorMessage = MutableLiveData<String>()
    val errorMessage: LiveData<String> = _errorMessage


    private val _dataSourceType = MutableLiveData<DataSourceType>()
    val dataSourceType: LiveData<DataSourceType> = _dataSourceType

    private val repository: HomeRepository = HomeRepositoryProvider.provideHomeRepository()

    init {
        // 初始化当前数据源类型
        _dataSourceType.value = HomeRepositoryProvider.getCurrentDataSourceType()
    }

    /**
     * 加载首页数据
     */
    fun loadHomeData() {
        _isLoading.value = true
        _errorMessage.value = "" // 清除之前的错误消息

        viewModelScope.launch {
            try {
                withTimeout(10000L) {
                    val result = repository.getHomeData()

                    withContext(Dispatchers.Main) {
                        if (result.isSuccess) {
                            _sections.value = result.getOrThrow()
                            _errorMessage.value = ""
                        } else {
                            val exception = result.exceptionOrNull()
                            handleError(exception)
                        }
                        _isLoading.value = false
                    }
                }
            } catch (e: TimeoutCancellationException) {
                withContext(Dispatchers.Main) {
                    _errorMessage.value = "请求超时，服务器可能已关闭"
                    _isLoading.value = false
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    handleError(e)
                    _isLoading.value = false
                }
            }
        }
    }

    /**
     * 处理各种网络错误，提供用户友好的错误信息
     */
    private fun handleError(exception: Throwable?) {
        val errorMsg = when (exception) {
            is UnknownHostException -> "无法连接到服务器，请检查网络设置"
            is ConnectException -> "连接服务器失败，服务器可能已关闭"
            is SocketTimeoutException -> "请求超时，请稍后重试"
            else -> exception?.message ?: "未知错误"
        }
        _errorMessage.value = errorMsg
    }

    /**
     * 刷新数据
     */
    fun refreshData() {
        _errorMessage.value = ""
        loadHomeData()
    }

    /**
     * 重新加载失败的数据
     */
    fun retryLoadData() {
        _errorMessage.value = ""
        loadHomeData()
    }
    
    /**
     * 切换数据源类型
     */
    fun switchDataSource(type: DataSourceType) {
        if (type != _dataSourceType.value) {
            HomeRepositoryProvider.switchDataSource(type)
            _dataSourceType.value = type
            refreshData()
        }
    }
    
    /**
     * 切换到下一个数据源类型
     */
    fun toggleDataSource() {
        val newType = when (_dataSourceType.value) {
            DataSourceType.MOCK -> DataSourceType.NETWORK
            DataSourceType.NETWORK -> DataSourceType.MOCK
            else -> DataSourceType.MOCK
        }
        switchDataSource(newType)
    }
}